<template>
  <div class="layout-col flex2 bss">
    <div class="ww100 flex-bc plr12 ptb8 bs4">
      <div class="flex-sc">
        <span class="f15 fw">控制点</span>
      </div>
      <div class="flex-ec flex1 h32">
        <el-button class="bgi3 white" @click.stop="toPath('/sensor')" v-if="!isNull(publicStore.form)">返回</el-button>
        <el-button class="bgi3 white" @click.stop="asyncAction()">同步</el-button>
      </div>
    </div>
    <div class="row bgi22">
      <div :style="{textAlign: v.align, paddingRight: v.name=='操作'?'10px': 'inherit'}" v-for="(v, i) in state.content" :key="i" v-show="v.show" :class="v.width">{{v.name}}</div>
    </div>
    <div class="flex1 overlay ww100 flex-col-ss">
      <el-tree 
      class="ww100" 
      ref="treeRef" 
      :data="state.tree"
      :node-key="state.key" 
      :current-node-key="defaultId"
      :props="defaultProps"
      highlight-current    
      accordion
      @node-click="handleNodeClick"
      empty-text="暂无数据">
        <template #default="{ node, data }">
          <span class="row">
            <div v-show="v.show" :class="v.width" :style="{textAlign: v.align}" v-for="(v, i) in state.content" :key="i">
              <span v-if="typeof(v.key) == 'object'" class="i21 cursor mlr5" v-for="(vv, kk, ii) in v.key" :key="ii" :class="kk=='add'?'none':''" @click.stop="handleClick(kk, data)">{{vv}}</span>
              <span v-else-if="v.key=='*'">{{index+1}}</span>
              <span v-else>{{isNull(data[v.key]) && v.key!=''? '/' : data[v.key]}}</span>
            </div>
          </span>
        </template>
      </el-tree>
    </div>
    <Add @init="init" :state="state" ref="exposeRef" />
  </div>
</template>

<script lang="ts" setup>
  import api from '@/api'
  const route = useRoute()
	const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  const state = reactive({
	  ...publicStore.$state,
    key: 'id',
    parent: 'parent_id',
    content: [
      { width: 'flex1', show: true, align: 'start', key: 'name', name: '名称' }, 
    ],
  })
  let exposeRef = $ref()
  let treeRef = $ref()
  let defaultProps = {
    children: 'children',
    label: 'name',
  }
  let defaultId = $ref()
  let expandNode = $ref('')

  onMounted(async() => {
    publicStore.form = route.query
    init()
  })

  const init = async() => {
    let query = {"o": "o_sensor", "p": [publicStore.distributId], "i": 0}
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    let sensorList = proxy.isNull(res)? [] : res
    publicStore.list = sensorList
    let query2 = getQuery(sensorList)
    let params2 = {queryApi2: query2}
    let res2 = await publicStore.post(params2)
    let controlList = proxy.isNull(res2)? [] : res2
    let list = getList(sensorList, controlList)
    state.list = sensorList.concat(list)
    state.tree = proxy.treeData(state.list, state.key, state.parent, 'children')
    let node = proxy.findNode(state.tree, (node) => { return defaultId? node[state.key] == defaultId : !node.children })
    await nextTick()
    handleNodeClick(node)
  }

  const getQuery = (val) => {
    let tempArr = [] 
    val.filter(a=>a.class == 0).forEach(v => {
        let exist = tempArr.find(a=>a.p[0] == v.type)
        if(!exist) tempArr.push({"o":"o_sensor_template_control_property","p":[v.type]})
    })
    return tempArr
  }

  const getList = (sensorList, controlList) => {
    let tempArr = [] 
    sensorList.filter(a=>a.class == 0).forEach(v => {
        let arr = controlList.filter(a=>a.sensor_type == v.type)
        if(arr){
          arr.forEach((vv, ii) => {
            delete vv.id
            let temp = Object.assign({id: v.id + '_' +vv.code + '_' + ii, parent_id: v.id}, vv)
            if(!defaultId && publicStore.form[state.key] && publicStore.form[state.key] == v[state.key]) defaultId = temp.id
            tempArr.push(temp)
          })
        }
    })
    return tempArr
  }

  const handleNodeClick = async(val) => {
    defaultId = val[state.key]
    treeRef.setCurrentKey(defaultId, true)
    publicStore.active = val
  }

  // 同步
  const asyncAction = async() => {
     ElMessageBox.confirm('是否确定同步到同类型设备?', '重要提示！', {
      confirmButtonText: '确定',
      cancelButtonText: '关闭',
      type: 'error'
    }).then(async() => {
      expandNode = publicStore.active.hasOwnProperty('children')? publicStore.active : proxy.findNode(state.tree, (node) => { return node[state.key] == publicStore.active.parent_id })
      let query = {"o": "o_sensor_control_action", "p":[expandNode.id], "i": 0}
      let params = {queryApi: query}
      let actionList = await publicStore.post(params)
      if(proxy.isNull(actionList)) return
      let asyncData = publicStore.list.filter(a=>a.type == expandNode.type)
      let delQuery = await getDelQuery(asyncData)
      let addQuery = await getAddQuery(asyncData, actionList)
      await onAdd(addQuery, delQuery)
    })
  }

  const getDelQuery = async(asyncData) =>{
    let delArr = []
    let queryArr = []
    asyncData.forEach((v, i) => {
      let query = {"o": "o_sensor_control_action", "p":[v.id], "i": 0}
      queryArr.push(query)
    });
    let params = {queryApi: queryArr}
    let res = await publicStore.post(params)
    res.forEach(v => {
      let del = {"a": '删除', "o": 'o_sensor_control_action', "t": 'del', id: v.id}
      delArr.push(del)
    })
    return delArr
  }

  const getAddQuery = async(asyncData, actionList) =>{
    let addArr = []
    let queryArr = []
    asyncData.forEach((v, i) => {
      actionList.forEach((vv, ii) => {
        let add = {
          "a": '同步', 
          "o": 'o_sensor_control_action', 
          "t": 'add', 
          id: (new Date().getTime() + (i+1)*100 + (ii+1)) + '',
          sensor_id: v.id,
          code_name: vv.code_name,
          code: vv.code,
          action: vv.action,
          name: vv.name,
          description: vv.description,
          action_type: vv.action_type,
        }
        addArr.push(add)
      })
    })
    return addArr
  }

  const onAdd = async(addQuery, delQuery) =>{
    if(proxy.isNull(addQuery)) return
    api.updateApi(addQuery).then((res) => {
      if(res.errcode == 0){
        ElNotification({ title: '提示', message: '同步成功', type: 'success' })
        if(proxy.isNull(delQuery)) return
        onDel(delQuery)
      }
    }).catch((err) => {
        ElNotification({ title: '提示', message: '同步失败', type: 'error' })
    })
  }

  const onDel = async(delQuery) =>{
    api.updateApi(delQuery).then((res) => {
    if(res.errcode == 0){
        ElNotification({ title: '提示', message: '清理成功', type: 'success' })
      }
    }).catch((err) => {
        ElNotification({ title: '提示', message: '清理失败', type: 'error' })
    })
  }

</script>
  
<style scoped lang="scss">

</style>
  